package com.beney.messageHandler;

import com.beney.codec.MessagePacket;
import com.beney.message.MessageHandler;
import com.beney.message.auth.AuthReq;
import com.beney.message.auth.AuthResp;
import com.beney.server.ChannelManager;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthReqHandler implements MessageHandler<AuthReq> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ChannelManager channelManager;

    @Override
    public void handle(Channel ch, AuthReq message) {
        String token;
        if (isEmpty(token = message.getToken())) {
            AuthResp authResp = new AuthResp()
                    .setCode(AuthResp.CODE_FAIL)
                    .setMessage("token 为空");
            ch.writeAndFlush(new MessagePacket(AuthResp.TYPE, authResp));
            return;
        }

        // TODO: token 的验证

        // TODO: 从 token 解析出用户名, 作为索引
        channelManager.channelBindUser(ch, token);

        // 认证成功
        AuthResp authResp = new AuthResp()
                .setCode(AuthResp.CODE_SUCCESS);
        ch.writeAndFlush(new MessagePacket(AuthResp.TYPE, authResp));
    }

    @Override
    public String messageType() {
        return AuthReq.TYPE;
    }

    private boolean isEmpty(String s) {
        return s == null || s.equals("");
    }
}
